import json
import requests
from PyQt5.QtGui import QPixmap
from PyQt5.QtNetwork import QNetworkRequest

from qtThread import QtThread


class Login:
    def __init__(self, mainWindow):
        self.mainWindow = mainWindow
        self.ui = mainWindow.ui.login

        # 加载 logo 图片
        pixmap = QPixmap('icons/20x20/SF_logo.png')  # 按指定路径找到图片
        self.ui.logo.setPixmap(pixmap)
        self.ui.logo.setScaledContents(True)
        self.ui.login.clicked.connect(self.login)

    def loadData(self):
        # try:
        #     request = QNetworkRequest()
        #     request.setUrl('http://127.0.0.1:5000/passport/getCaptcha')
        #     pixmap = QPixmap()
        #     pixmap.loadFromData()
        # except:
        #     print("网络错误，无法获取验证码")
        print("Hello World")

    def login(self):
        # 登录
        url = self.mainWindow.url + '/passport/qtLogin'
        username = self.ui.edit_username.text()
        password = self.ui.edit_password.text()
        userInfo = {'username': username, 'password': password}

        url = self.mainWindow.url + '/passport/qtLogin'
        userInfo = {'username': username, 'password': password}
        response = requests.post(url, data=userInfo)

        response = self.mainWindow.session.post(url, data=userInfo)
        text = json.loads(response.text)
        success = text['success']
        if success:

            # 登陆后获取到的cookie保存到mainWindow的cookie中
            self.mainWindow.cookies = self.mainWindow.session.cookies.get_dict()

            # 把登录后的cookie赋值到QWebEngineView中，使QWebEngineView也能获得访问权限
            self.mainWindow.web.initCookies()

            # 如果登录成功就显示被隐藏的按钮
            self.ui.label_msg.setText('')
            self.mainWindow.enableButton("btn_home")
            self.mainWindow.enableButton("btn_home")
            self.mainWindow.enableButton("btn_emergency")
            self.mainWindow.enableButton("btn_scene")
            self.mainWindow.enableButton("btn_psychology")
            self.mainWindow.enableButton("btn_course")
            self.mainWindow.enableButton("btn_web")
            self.mainWindow.enableButton("btn_widgets")
            self.mainWindow.enableButton("btn_personal")
            # self.mainWindow.enableButton('btn_external')

            # 隐藏登录页面
            self.mainWindow.disableButton("btn_login")

            # 显示退出按钮
            # self.mainWindow.ui.btn_logout.setHidden(False)
            self.mainWindow.enableButton('btn_logout')

            # 设置左下角显示用户名
            self.mainWindow.ui.label_user_icon.setText(username)

            # 显示右下角用户名
            self.mainWindow.ui.label_user_icon.setHidden(False)

            # 登陆后页面跳转至主页
            self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)
            self.mainWindow.web.loadData()

            self.mainWindow.isLogin = True

            # 开启应急演练状态检测轮询
            self.mainWindow.isPolling = True
            self.mainWindow.thread_check_emergency_status()

            # 登录本系统的同时登录课题四的系统
            # self.emergencyLoginThread = QtThread(url=self.mainWindow.emergencyUrl + '/login',
            #                                      header={
            #                                          'content-type': "application/json"
            #                                      },
            #                                      method='POST',
            #                                      data=json.dumps(
            #                                          {
            #                                              "username": self.mainWindow.emergencyUsername,
            #                                              "password": self.mainWindow.emergencyPassword
            #                                          }))
            # self.emergencyLoginThread.load_data.connect(self.emergencyLogin)
            # self.emergencyLoginThread.run()

        else:
            self.ui.label_msg.setText(text['msg'])



    def getCaptcha(self):
        try:
            request = QNetworkRequest()
            request.setUrl(self.mainWindow.url + '/passport/getCaptcha')
            pixmap = QPixmap()
            pixmap.loadFromData()
        except:
            print("网络错误，无法获取验证码")

    def emergencyLogin(self, text):
        if text['data'] is None:
            print('课题四登录错误')
        else:
            self.mainWindow.emergencyToken = text['data']['token']
